package com.ourteam.system.api;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.Subject;

import com.ourteam.frame.web.ApplicationModel;
import com.ourteam.system.domain.SystemModule;
import com.ourteam.system.domain.SystemRole;
import com.ourteam.system.service.ISysRoleService;
import com.ourteam.system.service.ISystemApplicationService;
import com.ourteam.system.service.SysRoleServiceFactory;
import com.ourteam.system.service.SystemApplicationServiceFactory;

import net.ui.model.action.ActionBean;

public class AuthorityUtils {

	private static final ISysRoleService SYS_ROLE_SERVICE = SysRoleServiceFactory
			.getSysRoleService();

	private static final ISystemApplicationService SYSTEM_APPLICATION_SERVICE = SystemApplicationServiceFactory
			.getSystemApplicationService();

	public static long[] getAccountRoles(Subject subject) throws Exception {

		ApplicationModel applicationModel = (ApplicationModel) subject
				.getPrincipal();

		SystemRole[] systemRoles = SYS_ROLE_SERVICE
				.getSysUserRoles(applicationModel.getUserId());

		long[] roleIds = new long[systemRoles.length];

		for (int i = 0; i < systemRoles.length; i++) {
			SystemRole systemRole = systemRoles[i];

			roleIds[i] = systemRole.getId();
		}

		return roleIds;

	}

	public static boolean canExecuteAction(Subject subject,String moduleId,
			ActionBean actionBean) throws Exception {
		
		if(StringUtils.isEmpty(moduleId)){
			return true;
		}

		String actionCode = actionBean.getHandler();

		if (StringUtils.isBlank(actionBean.getHandler())) {
			actionCode = actionBean.getId();
		}

		SystemModule systemModule = SYSTEM_APPLICATION_SERVICE
				.getSystemModuleById(Long.parseLong(moduleId));

		long[] roleIds = getAccountRoles(subject);

		for (int i = 0; i < roleIds.length; i++) {
			if (SYS_ROLE_SERVICE.isSysRoleHasAction(roleIds[i],
					systemModule.getDomainCode(), systemModule.getModuleCode(),
					actionCode)) {
				return true;
			}
		}

		return false;
	}
}
